/**
 * @file background.js
 * @description 后台服务脚本，处理插件的后台任务
 */

// 插件安装或更新时的处理
chrome.runtime.onInstalled.addListener(details => {
    if (details.reason === 'install') {
        // 首次安装时的处理
        chrome.storage.local.set({
            settings: {
                theme: 'light',
                autoSave: false,
                saveFormat: 'markdown'
            }
        });
    }
});

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'saveToLocal') {
        handleSaveToLocal(request.data, sendResponse);
        return true; // 保持消息通道开放
    }
});

/**
 * 处理本地保存
 * @param {Object} data 要保存的数据
 * @param {Function} sendResponse 回调函数
 */
async function handleSaveToLocal(data, sendResponse) {
    try {
        const { title, markdown } = data;
        const filename = `${title.replace(/[<>:"/\\|?*]+/g, '_')}.md`;
        const blob = new Blob([markdown], { type: 'text/markdown' });
        
        await chrome.downloads.download({
            url: URL.createObjectURL(blob),
            filename: filename,
            saveAs: true
        });
        
        sendResponse({ success: true });
    } catch (error) {
        console.error('保存失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

// 添加右键菜单
chrome.runtime.onInstalled.addListener(() => {
    chrome.contextMenus.create({
        id: 'saveAsMarkdown',
        title: '保存为Markdown',
        contexts: ['page', 'selection']
    });
});

// 处理右键菜单点击
chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === 'saveAsMarkdown') {
        chrome.tabs.sendMessage(tab.id, {
            action: 'getPageContent',
            selection: info.selectionText
        });
    }
}); 